<?php

class ModuleService extends FServiceBase
{    
    /**
    * Generate module.php config file in runtime
    */
    public function generateConfigFile($params = array()) {
        $dbModules = Module::model()->findAll('enabled = true AND is_system = false');
        
        $config = array();
        foreach($dbModules as $module){
            $mConfig = array(
                'class' => "site.{$module->name}.{$module->name}Module",
            );
            // todo: load module config into $mConfig
            
            $config[$module->name] = $mConfig;
        }
        $str = '<?php return '.var_export($config, true).'; ?>';
        file_put_contents(Yii::app()->runtimePath.'/modules.php',$str);
    }
    
    
    /**
    * Get a Module model given its ID
    * 
    * @param int id Module ID
    * @return FServiceModel
    */
    public function get($params){
        $model = Module::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Module','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        /**
        * @var CModel
        */
        $model = $this->getModel($params['Module'],'Module');
        $this->result->processed('model', $model);
        
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Module', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        elseif (! $model->save())
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Admin.Module','Error while saving submitted data into database.'));
        
        return $this->result;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Admin.Module','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = Module::model()->findByPk($id);
            /**
            * TODO: Check related data if this Module is deletable
            * This can be done in onBeforeDelete or here or in extensions
            *
            if (Related::model()->count("ModuleId = {$id}") > 0)
                $this->result->fail(ERROR_VIOLATING_BUSINESS_RULES, Yii::t('Admin.Module',"Cannot delete Module ID={$id} as it has related class data."));
            else
            */
                try {
                    $model->delete();
                } catch (CDbException $ex) {
                    $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
                }
        }
        return $this->result;
    }
}